//
//  FriendDetailViewController.m
//  SouthChina
//
//  Created by Mr.Y on 15/1/7.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "FriendDetailViewController.h"
#import "ContactDetailController.h"
#import "ContactDao.h"
#define LABEL_HEIGHT 20
#define LABEL_WIDTH 60
@interface FriendDetailViewController ()<UIAlertViewDelegate,UITextFieldDelegate>
{
    UITextField * validationText;
    UIScrollView * friendScrollView;
}
@end

@implementation FriendDetailViewController
@synthesize friendInfoDic,validationStr,message,onOperateListener,friendtype;

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [self addTitleBarWithBackBtn:@"用户详情" needReturn:YES];
    //20151012
    friendScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, TITLE_BAR_HEGIHT+YNEW, SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW)];
    
    [self.view addSubview:friendScrollView];
    
    [self.view setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
    
    UIImageView * headImage = [[UIImageView alloc] initWithFrame:CGRectMake(20, 10, 50, 50)];
    NSString *headStr = [friendInfoDic objectForKey:@"headImg"];
    NSURL *url= [NSURL URLWithString: [headStr hasPrefix:@"http"]?headStr:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,headStr]];
    NSLog(@"&&&&&&&&&&&&&&&&&& %@",url);
    headImage.layer.masksToBounds = YES;
    headImage.layer.cornerRadius = 25.0;
    [headImage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
    [friendScrollView addSubview:headImage];
    
     UILabel * nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(30+headImage.frame.size.width,headImage.frame.origin.y, 180, 21)];
      nameLabel.text = [NSString stringWithFormat:@"%@(%@)",[friendInfoDic objectForKey:@"userName"],[[friendInfoDic objectForKey:@"type"] isEqualToString:@"T"]?@"教职工":@"学生"];
    nameLabel.font = [UIFont boldSystemFontOfSize:16.0f];
    [friendScrollView addSubview:nameLabel];
    
    UIView * infoView = [[UIView alloc] initWithFrame:CGRectMake(0,headImage.frame.origin.y+10+headImage.frame.size.height, SCREEN_WIDTH, 250)];
    [infoView setBackgroundColor:[UIColor whiteColor]];
    [friendScrollView addSubview:infoView];
    
    UILabel * sexLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,15, LABEL_WIDTH, LABEL_HEIGHT)];
    sexLabel.text = @"性别：";
    sexLabel.font = [UIFont systemFontOfSize:15.0f];
    [infoView addSubview:sexLabel];
    
    UILabel * sexDetailLabel = [[UILabel alloc] initWithFrame:CGRectMake(LABEL_WIDTH+40,sexLabel.frame.origin.y, LABEL_WIDTH, LABEL_HEIGHT)];
    sexDetailLabel.font = [UIFont systemFontOfSize:15.0f];
    
    sexDetailLabel.text = [friendInfoDic objectForKey:@"sex" ];
    [infoView addSubview:sexDetailLabel];
    //性别有下划线
    UILabel * sexLabelbg = [[UILabel alloc] initWithFrame:CGRectMake(0,sexLabel.frame.origin.y+35, self.view.frame.size.width, 1)];
    sexLabelbg.backgroundColor = [UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1];
    [infoView addSubview:sexLabelbg];
    
    UILabel * collegeLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,sexLabelbg.frame.origin.y+15, LABEL_WIDTH, LABEL_HEIGHT)];
    collegeLabel.text = @"学院：";
    collegeLabel.font = [UIFont systemFontOfSize:15.0f];
    [infoView addSubview:collegeLabel];
    
    UILabel * collegeDetailLabel = [[UILabel alloc] initWithFrame:CGRectMake(LABEL_WIDTH+40,collegeLabel.frame.origin.y, 200, LABEL_HEIGHT)];
    collegeDetailLabel.text = [friendInfoDic objectForKey:@"dept" ];
    collegeDetailLabel.font = [UIFont systemFontOfSize:15.0f];
    [infoView addSubview:collegeDetailLabel];
    //学院下划线
    UILabel * collegeLabelbg = [[UILabel alloc] initWithFrame:CGRectMake(0,collegeLabel.frame.origin.y+35, self.view.frame.size.width, 1)];
    collegeLabelbg.backgroundColor = [UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1];
    [infoView addSubview:collegeLabelbg];
    
    UILabel * validationLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,collegeLabelbg.frame.origin.y+15, 120, LABEL_HEIGHT)];
    if([friendtype isEqualToString:@"1"])//来自通讯录添加好友
        validationLabel.text = @"好友验证信息：";
    else if([friendtype isEqualToString:@"2"]|| [friendtype isEqualToString:@"3"]) //来自验证好友消息或者批准入群
        validationLabel.text = @"验证信息：";
    validationLabel.font = [UIFont systemFontOfSize:15.0f];
    [infoView addSubview:validationLabel];
    
    validationText = [[UITextField alloc] initWithFrame:CGRectMake(validationLabel.frame.size.width+validationLabel.frame.origin.x,validationLabel.frame.origin.y-(YNEW)/4, infoView.frame.size.width-160, 30)];
    validationText.borderStyle=UITextBorderStyleNone;
    validationText.delegate = self; //20151012
    validationText.text = validationStr?validationStr:@"";
    validationText.placeholder = @"请输入验证信息（必填）";
    validationText.font = [UIFont systemFontOfSize:14.0f];
    //setGroupName.delegate = self;
    [infoView addSubview:validationText];
    
    
    NSLog(@"类型：%@",[friendInfoDic objectForKey:@"type"]);
    if ([[friendInfoDic objectForKey:@"type"] isEqualToString:@"T"]) {
        collegeLabel.text = @"部门：";
        infoView.frame = CGRectMake(0,headImage.frame.origin.y+10+headImage.frame.size.height, SCREEN_WIDTH, 150);
        validationLabel.frame =CGRectMake(20,collegeLabel.frame.origin.y+25+LABEL_HEIGHT, 120, 30);
        validationText.frame =CGRectMake(validationLabel.frame.size.width+validationLabel.frame.origin.x,collegeLabel.frame.origin.y+25+LABEL_HEIGHT, infoView.frame.size.width-160, 30);
        
    }else  //学生额外显示专业和班级
    {
        collegeLabel.text = @"学院：";
        //专业
        UILabel * majorLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,collegeLabelbg.frame.origin.y+15, LABEL_WIDTH, LABEL_HEIGHT)];
        majorLabel.text = @"专业：";
        majorLabel.font = [UIFont systemFontOfSize:15.0f];
        [infoView addSubview:majorLabel];
        UILabel * majorDetailLabel = [[UILabel alloc] initWithFrame:CGRectMake(LABEL_WIDTH+40,majorLabel.frame.origin.y, 200, LABEL_HEIGHT)];
        majorDetailLabel.font = [UIFont systemFontOfSize:15.0f];
        majorDetailLabel.text = [friendInfoDic objectForKey:@"profName" ];
        [infoView addSubview:majorDetailLabel];
        //专业下划线
        UILabel * majorLabelbg = [[UILabel alloc] initWithFrame:CGRectMake(0,majorLabel.frame.origin.y+35, self.view.frame.size.width, 1)];
        majorLabelbg.backgroundColor = [UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1];
        [infoView addSubview:majorLabelbg];
        
        
        //班级
        UILabel * classLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,majorLabelbg.frame.origin.y+15, LABEL_WIDTH, LABEL_HEIGHT)];
        classLabel.text = @"班级：";
        classLabel.font = [UIFont systemFontOfSize:15.0f];
        [infoView addSubview:classLabel];
        UILabel * classDetailLabel = [[UILabel alloc] initWithFrame:CGRectMake(LABEL_WIDTH+40,classLabel.frame.origin.y, 200, LABEL_HEIGHT)];
        classDetailLabel.font = [UIFont systemFontOfSize:15.0f];
        classDetailLabel.text = [friendInfoDic objectForKey:@"className" ];
        [infoView addSubview:classDetailLabel];
        //班级下划线
        UILabel * classLabelbg = [[UILabel alloc] initWithFrame:CGRectMake(0,classLabel.frame.origin.y+35, self.view.frame.size.width, 1)];
        classLabelbg.backgroundColor = [UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1];
        [infoView addSubview:classLabelbg];
        validationLabel.frame =CGRectMake(20,classLabelbg.frame.origin.y+15, 120, 30);
        validationText.frame =CGRectMake(validationLabel.frame.size.width+validationLabel.frame.origin.x,classLabelbg.frame.origin.y+15, infoView.frame.size.width-160, 30);
    }
    
   
    
    //添加好友
    UIImage *img=[UIImage imageNamed:@"blue_btn_normal.png"];
    img=[img stretchableImageWithLeftCapWidth:20 topCapHeight:20];
    UIButton * addFriendBtn = [[UIButton alloc] initWithFrame:CGRectMake(10,infoView.frame.size.height+infoView.frame.origin.y+20, (SCREEN_WIDTH)-20, 35)];
    [addFriendBtn setBackgroundImage:img forState:UIControlStateNormal];
    [addFriendBtn addTarget:self action:@selector(addFriendBtn:) forControlEvents:UIControlEventTouchUpInside];
    [addFriendBtn setTitle:@"添加好友" forState:UIControlStateNormal];
    [friendScrollView addSubview:addFriendBtn];
    //拒绝按钮
    
    UIButton * refusedBtn = [[UIButton alloc] initWithFrame:CGRectMake(10,addFriendBtn.frame.size.height+addFriendBtn.frame.origin.y+50, (SCREEN_WIDTH)-20, 35)];
    [refusedBtn setBackgroundImage:img forState:UIControlStateNormal];
    [refusedBtn addTarget:self action:@selector(refusedBtn:) forControlEvents:UIControlEventTouchUpInside];
    [refusedBtn setTitle:@"拒绝" forState:UIControlStateNormal];
    refusedBtn.hidden = YES;
    [friendScrollView addSubview:refusedBtn];
    
    friendScrollView.bounces = NO;
    [friendScrollView setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
    [friendScrollView setShowsHorizontalScrollIndicator:NO];
    [friendScrollView setShowsVerticalScrollIndicator:NO];
    friendScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, addFriendBtn.frame.origin.y+addFriendBtn.frame.size.height+30);
    
    //验证消息(好友验证或者入群申请)
    if (validationStr) {
        validationLabel.text = @"验证信息：";
        if([friendtype isEqualToString:@"2"]) //好友验证
        {
            //20151010
            NSString * str =[NSString stringWithFormat:@"%@_%@_Friend",DE.userId,[friendInfoDic objectForKey:@"userId" ]];
            if ([ContactDao isMyFriend:str]) {
                addFriendBtn.hidden = YES;
                refusedBtn.hidden = YES;
                return;
            }
            else
            {
                [addFriendBtn setTitle:@"通过好友" forState:UIControlStateNormal];
                refusedBtn.hidden = NO;
            }
        }
        else if([friendtype isEqualToString:@"3"])//入群申请
        {
            [addFriendBtn setTitle:@"批准入群" forState:UIControlStateNormal];
            refusedBtn.hidden = NO;
        }
       
    }
    else//添加好友
    {
         validationLabel.text = @"好友验证信息：";
    }
    
    /*
    UILabel * validationLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,classLabel.frame.origin.y+10+LABEL_HEIGHT, 120, LABEL_HEIGHT)];
    validationLabel.text = @"好友验证信息：";
    validationLabel.font = [UIFont boldSystemFontOfSize:15.0f];
    [infoView addSubview:validationLabel];
    
    validationText = [[UITextField alloc] initWithFrame:CGRectMake(validationLabel.frame.size.width+validationLabel.frame.origin.x,validationLabel.frame.origin.y-(YNEW)/4, infoView.frame.size.width-160, 30)];
    validationText.borderStyle=UITextBorderStyleNone;
    validationText.text = validationStr?validationStr:@"";
    validationText.placeholder = @"请输入验证信息（必填）";
    validationText.font = [UIFont boldSystemFontOfSize:14.0f];
//    setGroupName.delegate = self;
    [infoView addSubview:validationText];
    if ([[friendInfoDic objectForKey:@"type"] isEqualToString:@"T"]) {
        collegeLabel.text = @"部门：";
        infoView.frame = CGRectMake(0,headImage.frame.origin.y+10+headImage.frame.size.height, SCREEN_WIDTH, 100);
        validationLabel.frame =CGRectMake(20,collegeLabel.frame.origin.y+5+LABEL_HEIGHT, 120, 30);
        validationText.frame =CGRectMake(validationLabel.frame.size.width+validationLabel.frame.origin.x,collegeLabel.frame.origin.y+5+LABEL_HEIGHT, infoView.frame.size.width-160, 30);
        
    }else
    {
        collegeLabel.text = @"学院：";
        [infoView addSubview:majorLabel];
        [infoView addSubview:majorDetailLabel];
        [infoView addSubview:classLabel];
        [infoView addSubview:classDetailLabel];
        
    }
    //添加好友
    UIImage *img=[UIImage imageNamed:@"blue_btn_normal.png"];
    img=[img stretchableImageWithLeftCapWidth:20 topCapHeight:20];
    UIButton * addFriendBtn = [[UIButton alloc] initWithFrame:CGRectMake(10,infoView.frame.size.height+infoView.frame.origin.y+30, (SCREEN_WIDTH)-20, 35)];
    [addFriendBtn setBackgroundImage:img forState:UIControlStateNormal];
    [addFriendBtn addTarget:self action:@selector(addFriendBtn:) forControlEvents:UIControlEventTouchUpInside];
    [addFriendBtn setTitle:@"添加好友" forState:UIControlStateNormal];
    [friendScrollView addSubview:addFriendBtn];
    //拒绝按钮

    UIButton * refusedBtn = [[UIButton alloc] initWithFrame:CGRectMake(10,addFriendBtn.frame.size.height+addFriendBtn.frame.origin.y+20, (SCREEN_WIDTH)-20, 35)];
    [refusedBtn setBackgroundImage:img forState:UIControlStateNormal];
    [refusedBtn addTarget:self action:@selector(refusedBtn:) forControlEvents:UIControlEventTouchUpInside];
    [refusedBtn setTitle:@"拒绝" forState:UIControlStateNormal];
    refusedBtn.hidden = YES;
    [friendScrollView addSubview:refusedBtn];

    friendScrollView.bounces = NO;
    [friendScrollView setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
    [friendScrollView setShowsHorizontalScrollIndicator:NO];
    [friendScrollView setShowsVerticalScrollIndicator:NO];
    friendScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, addFriendBtn.frame.origin.y+addFriendBtn.frame.size.height+30);

    if (validationStr) {
        NSString * str =[NSString stringWithFormat:@"%@_%@_friend_%@",DE.userId,[friendInfoDic objectForKey:@"userId" ],DE.userId];
        if ([ContactDao isMyFriend:str]) {
            addFriendBtn.hidden = YES;
            refusedBtn.hidden = YES;
            return;
        }
        else
        {
            [addFriendBtn setTitle:@"通过好友" forState:UIControlStateNormal];
            refusedBtn.hidden = NO;
        }



    }*/
   
    
    /*UILabel * majorLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,collegeLabel.frame.origin.y+10+LABEL_HEIGHT, LABEL_WIDTH, LABEL_HEIGHT)];
    majorLabel.text = @"专业：";
    majorLabel.font = [UIFont boldSystemFontOfSize:15.0f];
    */
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//20151012
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return  YES;
}

-(void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification
                                                  object:nil];
}

# pragma mark Keyboard Notifications

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    friendScrollView.frame = CGRectMake(0, TITLE_BAR_HEGIHT+YNEW, SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW-height);
}

- (void)keyboardWillHide:(NSNotification *)notification {
    friendScrollView.frame = CGRectMake(0, TITLE_BAR_HEGIHT+YNEW, SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW);
}


-(void)addFriendBtn:(id)sender
{
    [self colseKeyboard];
    
    if (validationStr) {
        [self throughFriend];
        return;
    }
    NSLog(@"%@",[DE getGlobalVar:LOGIN_USER_TYPE]);
    if (DE.userId != nil && [DE.userId isEqualToString:[friendInfoDic objectForKey:@"userId"]]) {
        [self showAlerHUD:@"不能添加自己为好友！"];
        return;
    }
    //20151010
    NSString * str =[NSString stringWithFormat:@"%@_%@_Friend",DE.userId,[friendInfoDic objectForKey:@"userId" ]];
    
    if ([friendInfoDic objectForKey:@"friendRange"] == [NSNull null]) {
        [self showAlerHUD:@"对方暂未打开好友添加功能！"];
        return;
    }
    /*else if (![[friendInfoDic objectForKey:@"friendRange"] containString:[DE getGlobalVar:LOGIN_USER_TYPE]])
      friendRange定义：T老师，S是学生，但是LOGIN_USER_TYPE定义是：T老师，其他是学生，学生类型有几种，这里friendRange与LOGIN_USER_TYPE的对应关系应该是
       friendRange=(LOGIN_USER_TYPE=="T"?"S")
     */
    else if (![[friendInfoDic objectForKey:@"friendRange"] containString:[[DE getGlobalVar:LOGIN_USER_TYPE] isEqualToString:@"T"]?@"T":@"S"])
    {
        [self showAlerHUD:@"对方暂未打开好友添加功能！"];
        return;
    }
    NSLog(@"DFAFAFAFASFAS%@",str);
    if ([ContactDao isMyFriend:str]) {
        [self showAlerHUD:[NSString stringWithFormat:@"%@已经在您的好友列表中了！",[friendInfoDic objectForKey:@"userName" ]]];
        return;
    }
    if ([validationText.text isEqualToString:@""]) {
        [self showAlerHUD:@"好友验证消息不能为空！"];
        return;
    }else
    {
        [self addFriend:[friendInfoDic objectForKey:@"userId"] message:validationText.text];

    }
    
}
-(void)addFriend:(NSString *)friendId message:(NSString *)messagee{
    NSDictionary *map = @{@"receiverId":friendId,@"validateMsg":messagee};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [DE serverCall:@"sendFriendReq" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if(success && data && [data objectForKey:@"result"])
        {
            //回退到上一级页面
            [self.navigationController popViewControllerAnimated:YES];
            //得到最上面那个viewcontroller
            ContactDetailController *viewC = [self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count-1)];
            
            [viewC showAlerHUD:@"发送好友验证消息成功!"];
        }
        else{
            [self showAlerHUD:@"发送好友验证消息失败！"];
        }
    }];

}
-(void)throughFriend
{
    
    [self.navigationController popViewControllerAnimated:NO];
    
    [onOperateListener onOperateButtonClick:message acceptOrNot:YES];
}

-(void)refusedBtn:(id)sender
{
    [self.navigationController popViewControllerAnimated:NO];
    [onOperateListener onOperateButtonClick:message acceptOrNot:NO];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}




@end
